/**
 * 判定数据对象是否合格
 * @param {object} params 待测试的数据对象
 * @param {Array} cases 检测条件 
 */
export default function checkValid(params, cases) {
    if (!params || !cases || cases.length <= 0) {
        throw new Error('Invalid arguments');
    }

    for (let i = 0; i < cases.length; i++) {
        if (checkSingleCase(params, cases[i]) === false) {
            return {
                valid: false,
                msg: cases[i].msg,
            }
        }
    }

    return {
        valid: true,
    };
}

function checkSingleCase(params, thecase) {
    const {
        key,
        required,
        phone,
        msg,
    } = thecase;

    const val = params[key];
    if (required && !val) return false;
    if (phone && !isPhone(val)) return false;

    return true;
}

function isPhone(val) {
    const PHONE = /^1\d{10}$/;
    return PHONE.test(val);
}
